package com.springboot.filter;

import com.springboot.common.MyFailureHandler;
import com.springboot.common.VerificationException;
import com.springboot.vo.Result;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class VerificationCoderFilter extends OncePerRequestFilter {

    private MyFailureHandler failureHandler = new MyFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        System.out.println("VerificationCoderFilter  doFilterInternal");
        //只有login操作，才需要这个过滤器使用
        String uri = httpServletRequest.getRequestURI();
        if (!"/login".equals(uri)){
            //过滤器正常执行，不参与验证码操作
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }else {
            //登录操作，需要验证code
            try {
                //验证code是否正确
                verificationCode(httpServletRequest);
                //如果验证通过过滤器正常执行
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }catch (VerificationException e){
                Result result = new Result();
                result.setCode(1);
                result.setError(1002);
                result.setMsg("验证码错误！！！");
                failureHandler.setResult(result);
                failureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }
        }


    }


    private void verificationCode(HttpServletRequest httpServletRequest){
        HttpSession session = httpServletRequest.getSession();

        //获取请求中的code
        String requestCode = httpServletRequest.getParameter("code");

        //获取session中的code
        Object attr = session.getAttribute("code");


        String sessionCode = "";
        if (attr != null){
            sessionCode = (String) attr;
        }

        System.out.println("VerificationCoderFilter  doFilterInternal  requestCode：" + requestCode + "|sessionCode:" + sessionCode);
        //处理逻辑
        if (!StringUtils.isEmpty(sessionCode)){
            //说明在session中有code，用户已经看到这个code了
            //如果能到这段代码，所以用户已经发起了登录请求
            //session中的code就应该无用
            session.removeAttribute("code");

        }

        //判断code是否正确
        if (StringUtils.isEmpty(requestCode) ||
                StringUtils.isEmpty(sessionCode) ||
                !requestCode.equals(sessionCode)){
            //失败
            throw new VerificationException();
        }
    }
}
